package com.gxc.blogm.service;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.gxc.blogm.domain.Article;
import com.gxc.dbcore.dao.SqlDao;
import com.gxc.dbcore.util.PageInfo;
import com.gxc.dbcore.util.PageList;
import com.gxc.webcore.util.ContextUtil;

public class ArticleService {

	SqlDao sqlDao;

	public SqlDao getSqlDao() {
		return sqlDao;
	}

	public void setSqlDao(SqlDao sqlDao) {
		this.sqlDao = sqlDao;
	}

	/**
	 * 获取单个文章
	 * 
	 * @param id
	 * @return
	 */
	public Article retrieve(String id) {
		return sqlDao.selectOne("blog.article.retrieve", id);
	}

	/**
	 * 获取单个文章并翻译字典
	 * 
	 * @param id
	 * @return
	 */
	// @SuppressWarnings("rawtypes")
	// public HashMap retrieve_tr(String id) {
	// Article article = this.retrieve(id);
	// return DicUtil.translateBean(article, new String[] { "type" });
	// }

	/**
	 * 创建新文章
	 * 
	 * @param article
	 * @return
	 */
	public int create(Article article) {
		int i = sqlDao.insert("blog.article.create", article);
		this.updateCache();
		return i;
	}

	/**
	 * 更新文章信息
	 * 
	 * @param article
	 * @return
	 */
	public int update(Article article) {
		int i = sqlDao.update("blog.article.update", article);
		this.updateCache();
		return i;
	}

	/**
	 * 删除单个文章
	 * 
	 * @param id
	 * @return
	 */
	public int delete(String id) {
		int i = sqlDao.delete("blog.article.delete", id);
		this.updateCache();
		return i;
	}

	/**
	 * 批量删除文章
	 * 
	 * @param id_array
	 * @return
	 */
	public int delete(String[] id_array) {
		int i = 0;
		for (String id : id_array) {
			i += sqlDao.delete("blog.article.delete", id);
		}
		this.updateCache();
		return i;
	}

	/**
	 * 列出所有文章
	 * 
	 * @param parameter
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List listAll(Map parameter) {
		List list = sqlDao.selectList("blog.article.list", parameter);
		return list;
		// return DicUtil.translateBean(list, new String[] { "type" });
	}

	/**
	 * 分页列出文章
	 * 
	 * @param parameter
	 * @param pageInfo
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public PageList listPage(Map parameter, PageInfo pageInfo) {
		PageList pagelist = sqlDao.selectPageList("blog.article.list",
				parameter, pageInfo);
		// List list = DicUtil.translateBean(pagelist.getList(),
		// new String[] { "type" });
		// pagelist.setList(list);
		return pagelist;
	}

	/**
	 * 按文章分类进行统计
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List statByType() {
		return sqlDao.selectList("blog.article.statByType");
	}

	/**
	 * 按文章创建年月进行统计
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List statByYearMonth() {
		List list = sqlDao.selectList("blog.article.statByYearMonth");
		for (HashMap item : (List<HashMap>) list) {
			if (item.get("create_time_month").toString().length() == 1) {
				item.put("create_time_month",
						"0" + item.get("create_time_month").toString());
			}
			String create_time = item.get("create_time_year") + "-"
					+ item.get("create_time_month");
			item.put("create_time", create_time);
			item.remove("create_time_year");
			item.remove("create_time_month");
		}
		return list;
	}

	/**
	 * 更新访问次数
	 * 
	 * @param id
	 * @return
	 */
	public int updateViewNum(String id) {
		return sqlDao.update("blog.article.updateViewNum", id);
	}

	/**
	 * 更新评论次数
	 * 
	 * @param id
	 * @return
	 */
	public int updateCommentNum(String id) {
		return sqlDao.update("blog.article.updateCommentNum", id);
	}

	/**
	 * 更新缓存
	 */
	private void updateCache() {
		CacheService cacheService = (CacheService) ContextUtil
				.getBean("blogCacheService");
		cacheService.reloadArticleSortList();
		cacheService.reloadArticleArchiveList();
	}

	/**
	 * 获取文章摘要
	 * 
	 * @param content
	 * @return
	 */
	public String getSummary(String content) {
		String summary = null;
		String dcontent = "<div>" + content + "</div>";
		// 替换dcontent中的"&"
		dcontent = dcontent.replace('&', '^');
		try {
			// String xmlStr = new String(content.getBytes(), "UTF-8");
			StringReader sr = new StringReader(dcontent);
			InputSource is = new InputSource(sr);
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			Document doc = docBuilder.parse(is);
			Element root = doc.getDocumentElement();
			NodeList nodeList = root.getChildNodes();
			while (nodeList.getLength() > 1) {
				root.removeChild(nodeList.item(1));
			}
			/*
			 * if(nodeList.getLength()>1){ for(int i=1;i < nodeList.getLength();
			 * i++){ root.removeChild(nodeList.item(i)); } }
			 */
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer t = tf.newTransformer();
			// t.setOutputProperty("encoding", "UTF-8");
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			t.transform(new DOMSource(doc), new StreamResult(bos));
			summary = bos.toString();
			summary = summary.replace('^', '&');
		} catch (Exception e) {
			e.printStackTrace();
		}
		return summary;
	}

	@SuppressWarnings("rawtypes")
	public PageList search(Map params, PageInfo pageInfo) {
		PageList pagelist = sqlDao.selectPageList("blog.article.search",
				params, pageInfo);
		// List list = DicUtil.translateBean(pagelist.getList(),
		// new String[] { "type" });
		// pagelist.setList(list);
		return pagelist;
	}
}
